package com.horizon.common.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

/**
 * 国际化配置
 *
 * @author wangfuwei
 * @version 2018-08-13
 */
@SpringBootConfiguration
public class I18NConfiguration implements WebMvcConfigurer {

    /**
     * 国际化语言参数名称
     */
    public static final String LOCAL_NAME = "l";

    @Autowired
    private Environment environment;

    /**
     * 设置cookie语言解析器
     */
    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
        cookieLocaleResolver.setCookieName("Language");
        cookieLocaleResolver.setCookieMaxAge(60 * 60 * 24 * 30);//30天有效期
        return cookieLocaleResolver;
    }

    /**
     * 注册国际化拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String staticPath = environment.getProperty("spring.mvc.static-path-pattern");
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName(LOCAL_NAME);
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(localeChangeInterceptor).addPathPatterns("/**");

        //忽略拦截静态资源
        if (!StringUtils.isEmpty(staticPath) && !staticPath.equals("/**")) {
            interceptorRegistration.excludePathPatterns(staticPath);
        }
    }
}
